﻿using System.ComponentModel;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace Dynamic.Api.Utils
{

    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class MvcBuilderExtensions
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddDynamicApi(this IMvcBuilder builder)
        {

            var feature = new ControllerFeature();

            foreach (AssemblyPart assemblyPart in builder.PartManager.ApplicationParts.OfType<AssemblyPart>())
            {
                foreach (var type in assemblyPart.Types)
                {
                    if (type.IsInterface && type.IsDefinedIncludingBaseInterfaces<DynamicApiAttribute>() && !type.IsDefined(typeof(NonDynamicApiAttribute)) && !type.IsGenericType)
                    {
                        feature.Controllers.Add(DynamicApiProxy.GetProxyType(type));  
                        Console.WriteLine($"继承于特性：DynamicApiInterface:{type.Name},Namespace:{type.Namespace}");
                    }  
                }
            }

            builder.AddApplicationPart(DynamicApiProxy.DynamicAssembly.AssemblyBuilder);

            builder.PartManager.FeatureProviders.Add(new DynamicApiControllerFeatureProvider());

            //builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IControllerPropertyActivator, DynamicApiControllerPropertyActivator>());

            builder.Services.Configure<MvcOptions>(o =>
            {
                o.Conventions.Add(new DynamicApiControllerConvention());
            });

            return builder;
        }

    }
}
